<template>
  <div class="editor-main" style="height:100vh;display:flex;flex-direction:column;">
    <!-- 分支选择器和分支管理 -->
    <div class="editor-toolbar">
      <el-select v-model="currentBranchId" placeholder="请选择分支" @change="onBranchChange" style="width:180px;">
        <el-option v-for="branch in branchList" :key="branch.id" :label="branch.name" :value="branch.id" />
      </el-select>
      <el-button @click="openBranchManager" style="margin-left:8px;">分支管理</el-button>
      <el-button type="primary" @click="openAddRoot" style="margin-left:16px;">新增成员</el-button>
      <!-- <el-button @click="openImport">批量导入</el-button> -->
      <el-button @click="exportMembers">导出</el-button>
      <el-input v-model="search" placeholder="搜索成员..." @input="doSearch" style="width:200px;margin:0 8px;" />
      <el-button @click="fetchTree">刷新</el-button>
    </div>
    <el-row :gutter="16" style="flex:1;min-height:0;">
      <el-col :span="14" style="height:100%;">
        <el-card style="height:100%;">
          <family-tree-graph
            v-if="treeData"
            :data="treeData"
            @node-click="handleNodeClick"
            @node-menu="handleNodeMenu"
            @node-drag="handleNodeDrag"
          />
        </el-card>
      </el-col>
      <el-col :span="10" style="height:100%;">
        <el-card style="height:100%;">
          <div v-if="selectedNode">
            <!-- 成员详情展示 -->
            <div style="text-align:center;margin-bottom:20px;">
              <el-avatar :src="selectedNode.photo" :size="150" style="margin-bottom:12px;border:2px solid #eee;box-shadow:0 2px 8px #f0f1f2;">
                <i class="el-icon-user" style="font-size:60px;" />
              </el-avatar>
            </div>
            <h3>{{ selectedNode.name }}</h3>
            <p>性别：{{ genderText(selectedNode.gender) }}</p>
            <p>世代：{{ selectedNode.generation }}</p>
            <p>分支：{{ selectedNode.branchName || '-' }}</p>
            <p>父亲：{{ selectedNode.fatherName || '-' }}</p>
            <div v-if="selectedNode.spouseList && selectedNode.spouseList.length > 0">
              <p>配偶：</p>
              <ul style="padding-left:20px;">
                <li v-for="spouse in selectedNode.spouseList" :key="spouse.id">
                  <span>{{ spouse.name }}</span>
                  <span v-if="spouse.relationType">（{{ spouse.relationType }}）</span>
                </li>
              </ul>
            </div>
            <div v-else>配偶：-</div>
            <p v-if="selectedNode.childOrder">排行：{{ selectedNode.childOrder }}</p>
            <p v-if="selectedNode.relationType">关系：{{ selectedNode.relationType }}</p>
            <el-divider />
            <el-button size="mini" type="primary" @click="openEditSelected">编辑</el-button>
            <el-button size="mini" @click="openAddChild">添加子成员</el-button>
            <el-button size="mini" type="danger" @click="deleteSelected">删除</el-button>
          </div>
          <div v-else style="color:#bbb;text-align:center;margin-top:200px;">请选择左侧成员节点</div>
        </el-card>
      </el-col>
    </el-row>
    <member-form
      :visible.sync="formVisible"
      :is-edit="isEdit"
      :form-data="formData"
      @submit="handleFormSubmit"
      @close="formVisible = false"
      :all-members="allMembers"
      :branch-list="branchList"
    />
    <!-- 分支管理弹窗、导入导出等弹窗可按需实现 -->
  </div>
</template>

<script>
import FamilyTreeGraph from './FamilyTreeGraph.vue';
import MemberForm from './MemberForm.vue';
import { getFamilyTreeWithRelation } from '@/api/familytree';
import { getMemberList } from '@/api/member';
import { getBranchList } from '@/api/branch';
import request from '@/api/request';
import { MessageBox, Message } from 'element-ui';

export default {
  name: 'FamilyTreeEditor',
  components: { FamilyTreeGraph, MemberForm },
  data() {
    return {
      branchList: [],
      currentBranchId: null,
      treeData: null,
      selectedNode: null,
      formVisible: false,
      isEdit: false,
      formData: {},
      search: '',
      allMembers: []
    };
  },
  created() {
    this.loadBranches();
  },
  methods: {
    async loadBranches() {
      const res = await getBranchList({ clanId: 1 }); // 1为示例，实际用当前家族ID
      this.branchList = res.records || [];
      if (this.branchList.length > 0) {
        this.currentBranchId = this.branchList[0].id;
        this.fetchTree();
      }
    },
    async onBranchChange(branchId) {
      this.currentBranchId = branchId;
      this.fetchTree();
    },
    async fetchTree() {
      if (!this.currentBranchId) return;
      this.treeData = await getFamilyTreeWithRelation({ branchId: this.currentBranchId });
      // 可选：同步加载所有成员用于下拉选择
      const memberRes = await getMemberList({ branchId: this.currentBranchId, page: 1, size: 1000 });
      this.allMembers = memberRes.records || [];
    },
    genderText(g) {
      if (g === 'M') return '男';
      if (g === 'F') return '女';
      return '-';
    },
    handleNodeClick(node) {
      this.selectedNode = node;
    },
    handleNodeMenu({ action, node }) {
      if (action === 'add') {
        this.isEdit = false;
        this.formData = { fatherId: node.id, branchId: this.currentBranchId, generation: (node.generation || 1) + 1 };
        this.formVisible = true;
      } else if (action === 'edit') {
        this.isEdit = true;
        this.formData = { ...node };
        this.formVisible = true;
      } else if (action === 'delete') {
        MessageBox.confirm('确定要删除该成员吗？', '提示', { type: 'warning' })
          .then(() => this.deleteMember(node.id))
          .catch(() => {});
      }
    },
    async handleFormSubmit(form) {
      if (this.isEdit) {
        await request.put(`/api/v1/members/${form.id}`, form);
        // 批量维护多配偶关系
        if (form.spouseIds && Array.isArray(form.spouseIds)) {
          await request.post('/api/v1/member-spouse/batch-update', {
            memberId: form.id,
            spouseIds: form.spouseIds
          });
        }
        Message.success('编辑成功');
      } else {
        const res = await request.post('/api/v1/members', { ...form, branchId: this.currentBranchId });
        // 新增后维护多配偶关系
        const memberId = res && res.data && res.data.id;
        if (memberId && form.spouseIds && Array.isArray(form.spouseIds)) {
          await request.post('/api/v1/member-spouse/batch-update', {
            memberId,
            spouseIds: form.spouseIds
          });
        }
        Message.success('新增成功');
      }
      this.formVisible = false;
      this.fetchTree();
    },
    async deleteMember(id) {
      await request.delete(`/api/v1/members/${id}`);
      Message.success('删除成功');
      this.fetchTree();
    },
    async handleNodeDrag({ draggedId, targetId }) {
      await request.post('/api/v1/family/tree/drag', { memberId: draggedId, newFatherId: targetId });
      Message.success('拖拽调整成功');
      this.fetchTree();
    },
    openAddRoot() {
      // 跳转到成员管理页面
      this.$router.push('/member');
    },
    openImport() {
      Message.info('批量导入功能待实现');
    },
    exportMembers() {
      Message.info('导出功能待实现');
    },
    doSearch() {
      Message.info('搜索功能待实现');
    },
    openEditSelected() {
      if (!this.selectedNode) return;
      this.isEdit = true;
      this.formData = { ...this.selectedNode };
      this.formVisible = true;
    },
    openAddChild() {
      if (!this.selectedNode) return;
      this.isEdit = false;
      this.formData = { fatherId: this.selectedNode.id, branchId: this.currentBranchId, generation: (this.selectedNode.generation || 1) + 1 };
      this.formVisible = true;
    },
    deleteSelected() {
      if (!this.selectedNode) return;
      MessageBox.confirm('确定要删除该成员吗？', '提示', { type: 'warning' })
        .then(() => this.deleteMember(this.selectedNode.id))
        .catch(() => {});
    },
    openBranchManager() {
      // 跳转到分支管理页面
      this.$router.push('/branch');
    }
  }
};
</script>

<style scoped>
.editor-main {
  padding: 20px;
}
.editor-toolbar {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}
</style> 